<template>
    <el-dialog v-model="dialogShow" title="设置链接" class="link-editor" width="600px">
      <el-form label-width="68px" label-position="right" style="max-width: 600px">
        <el-form-item label="链接类型">
          <el-radio-group v-model="editorForm.type">
            <el-radio :label="0">无</el-radio>
            <el-radio :label="1">栏目链接</el-radio>
            <el-radio :label="2">文章链接</el-radio>
            <el-radio :label="3">站外链接</el-radio>
          </el-radio-group>
        </el-form-item>
        <!-- 栏目链接 -->
        <el-form-item v-if="editorForm.type === 1" label="选择栏目">
          <el-tree-select v-model="editorForm.value1" placeholder="选择展示栏目" :data="allCategory" :props="selectProps" default-expand-all check-strictly style="width: 100%;" />
        </el-form-item>
        <!-- 文章链接 -->
        <el-form-item v-if="editorForm.type === 2" label="选择文章">
          <div class="add-user-box">
            <div class="person_body">
              <div class="person_tree">
                <el-select v-model="queryData.catId" @change="handleChangeCategory">
                  <el-option v-for="item in modelCategory" :key="item.id" :label="item.name" :value="item.id" />
                </el-select>
                <ul class="select-box" v-if="contentList.length" v-infinite-scroll="scrollLoad" :infinite-scroll-immediate="false">
                  <li v-for="item in contentList" :key="item.id" class="check_box">
                    <el-checkbox v-model="item.checked" @change="handleCheckChange(item)" size="large">
                      <template #default>
                        <div class="check-box-label">
                          <!-- <i class="iconfont"></i> -->
                          <span class="title">{{item.title}}</span>
                        </div>
                      </template>
                    </el-checkbox>
                  </li>
                </ul>
                <el-empty v-else description="该栏目下暂未发布内容" />
              </div>
              <div class="select-result">
                <p class="clear"><span>已选择{{selectedList.length}}篇</span>
                  <el-button type="danger" link @click="handleClearContent" :disabled="!selectedList.length">清空</el-button>
                </p>
                <ul>
                  <li v-for="(item, index) in selectedList" :key="item.data_id">
                    <span>{{item.title}}</span>
                    <i class="iconfont" @click="handleDeleteContent(item,index)">&#xeb6a;</i>
                  </li>
                </ul>
              </div>
            </div>
          </div>
        </el-form-item>
        <!-- 站外链接 -->
        <el-form-item v-if="editorForm.type === 3" label="自定义">
          <el-input v-model="editorForm.value3" placeholder="http://" clearable></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="handleCancel">取消</el-button>
          <el-button type="primary" @click="handleConfirm">确认</el-button>
        </span>
      </template>
    </el-dialog>
  </template>
  
  <script setup>
  import { ref, computed, reactive, watch, onMounted } from 'vue'
  import { useStore } from 'vuex'
  import { getAllCategory } from '@/api/category'
  import { getContentPage, getContentDetails } from "@/api/content"
  import { createTreeData } from '@ruifox-cms/utils'
  
  const props = defineProps({
    show: {
      type: Boolean,
      default: false
    },
    value: {
      type: Object,
      default: () => {}
    }
  })
  const emits = defineEmits(['update:show', 'update:value'])
  const store = useStore()
  const curEditorForm = computed(() => props.value)
  const editorForm = ref(structuredClone(curEditorForm.value)) // 由于链接设置是一个嵌套弹窗，需要保留上一个弹窗已修改的值所以不要直接修改
  const dialogShow = computed({
    get: () => props.show,
    set: (val) => {
      emits('update:show', val)
    }
  })
  // 获取栏目列表
  const allCategory = ref([])
  const modelCategory = ref([]) // 只取有数据模型的栏目
  const selectProps = reactive({
    children: 'children',
    label: 'name',
    value: 'id'
  })
  const _getAllCategory = async () => {
    const res = await getAllCategory({siteId: store.state.site.currentSite.id})
    if (res.code === 20000) {
      allCategory.value = createTreeData(res.data)
      modelCategory.value = res.data.filter(item => item.modelId)
    }
  }
  // 文章链接
  const contentList = ref([])
  const selectedList = ref([])
  const selectedIds = ref([])
  const tableLoading = ref(false)
  const total = ref(0)
  const defaultQueryData = reactive({
    currentPage: 1,
    pageSize: 20,
    catId: null // 默认为6，即新闻
  })
  const queryData = ref(Object.assign({}, defaultQueryData))
  const _getContentPage = async () => {
    tableLoading.value = true
    let res = await getContentPage(queryData.value)
    // 检测是否有已选择的，有就为其添加checked属性
    res.data.list.forEach(item => {
      if (selectedIds.value.includes(item.data_id)) {
        item.checked = true
      }
    })
    contentList.value.push(...res.data.list)
    total.value = res.data.total
    tableLoading.value = false
  }
  // 切换栏目，重新获取内容列表
  const handleChangeCategory = () => {
    queryData.value.currentPage = 1
    contentList.value = []
    _getContentPage()
  }
  // 触底加载内容列表
  const scrollLoad = () => {
    if (contentList.value.length === total.value) return
    queryData.value.currentPage++
    _getContentPage()
  }
  // 左侧切换文章勾选(只能选择一篇)
  const handleCheckChange = (data) => {
    // 只允许选择一篇文章
    if (selectedList.value.length) {
      selectedList.value[0].checked = false
      selectedList.value = []
    }
    if (data.checked) {
      selectedList.value.push(data)
    } else {
      const selectedIndex = selectedList.value.findIndex(item => item.id === data.id)
      if (selectedIndex !== -1) {
        selectedList.value.splice(selectedIndex, 1)
      }
    }
  }
  // 右侧删除文章
  const handleDeleteContent = (data, index) => {
    selectedList.value.splice(index, 1)
    const contentIndex = contentList.value.findIndex(item => item.id === data.id)
    if (contentIndex !== -1) {
      contentList.value[contentIndex].checked = false
    }
  }
  // 右侧清除全部已选
  const handleClearContent = () => {
    selectedList.value.forEach(item => {
      const contentIndex = contentList.value.findIndex(contentItem => contentItem.id === item.id)
      if (contentIndex !== -1) {
        contentList.value[contentIndex].checked = false
      }
    })
    selectedList.value = []
  }
  watch(selectedList, newVal => {
    let formatObj = {}
    let ids = []
    newVal.forEach(item => {
      const catId = item.cat_key
      if (!formatObj[catId]) {
        formatObj[catId] = {
          catId: catId,
          dataIds: []
        }
      }
      formatObj[catId].dataIds.push(item.data_id)
      ids.push(item.data_id)
    })
    editorForm.value.value2 = Object.values(formatObj).map(item => ({ ...item, catId: item.catId }))
    selectedIds.value = ids
  }, { deep: true })
  // 回显已选文章的详情
  const echoContentDetail = async () => {
    const res = await getContentDetails({ list: editorForm.value.value2 })
    if (res.code === 20000) {
      selectedList.value = res.data
      queryData.value.catId = res.data[0].cat_id
      handleChangeCategory()
    }
  }
  // 取消则还原默认
  const handleCancel = () => {
    editorForm.value = curEditorForm.value
    dialogShow.value = false
  }
  const handleConfirm = () => {
    curEditorForm.value = editorForm.value
    emits('update:value', editorForm.value)
    dialogShow.value = false
  }
  // 打开弹窗，初始化回显
  const dialogOpen = async () => {
    editorForm.value = structuredClone(curEditorForm.value)
    await _getAllCategory()
    // type==2即文章链接的值是一个栏目和内容id组成的数组
    const {type, value2} = editorForm.value
    if(type === 2 && value2 && value2.length > 0){
      echoContentDetail()
    }
  }
  
  onMounted(() => {
    dialogOpen()
  })
  </script>
  
  <style lang='scss' scoped>
  .link-editor{
    
  }
  .custom-next{
    width: 100%;
    padding-left: 80px;
  }
  .custom-after{
    display: inline-block;
    margin-left: 5px;
  }
  .el-radio-group .el-radio{
    margin-right: 8px;
  }
  </style>
  <style lang="scss">
  .link-editor {
    .add-user-box{
      width: 100%;
      .person_body {
        border: 1px solid #f5f5f5;
        height: 400px;
        display: flex;
        .person_tree {
          padding: 10px 12px 0 15px;
          width: 50%;
          height: 100%;
          border-right: 1px solid #f5f5f5;
          box-sizing:border-box;
          .select-box {
            height: 356px;
            overflow-y: auto;
            padding: 0;
            li {
              .el-checkbox__input{
                display: flex;
                align-items: center;
              }
              .check-box-label{
                display: flex;
                align-items: center;
                .title{
                  @include textEllipsis(18px, 1)
                }
              }
              i {
                float: right;
                padding-right: 10px;
                color: #3195f8;
                font-size: 14px;
                cursor: pointer;
              }
  
              a.active+i {
                color: rgb(197, 197, 197);
                // background-image: url(~@/assets/audit/next_level.png);
                pointer-events: none;
              }
  
              img {
                width: 14px;
                vertical-align: middle;
                margin-right: 5px;
              }
            }
          }
        }
        .select-result {
          width: 50%;
          height: 400px;
          font-size: 14px;
          overflow: hidden;
          p {
            padding: 9px 12px 0 15px;
            border-bottom: 1px solid #f2f2f2;
            display: flex;
            justify-content: space-between;
            align-items: center;
            line-height: 32px;
          }
          ul {
            height: 356px;
            overflow-y: auto;
            padding: 0 12px 0 15px;
            li {
              display: flex;
              justify-content: space-between;
              align-items: center;
              height: 40px;
              line-height: 40px;
              span {
                vertical-align: middle;
                @include textEllipsis(18px, 1)
              }
              i{
                font-size: 12px;
                color: #606266;
                cursor: pointer;
              }
              i:hover{
                color: $mainColor;
              }
            }
          }
    
        }
      }
    }
    .el-dialog__body .el-form .el-form-item .el-form-item__content .content-select.el-select-dropdown {
      .header-category {
        padding: 0 32px 0 20px;
        .el-radio-group .el-radio {
          .el-radio__input {
            display: none;
          }
          .el-radio__label {
            padding: 0 10px 6px 0;
          }
        }
      }
      .footer-page {
        padding: 0 32px 0 20px;
        width: 100%;
        box-sizing: border-box;
      }
    }
  }
  </style>